//
//  DragController.m
//  Simple Tagger
//
//  Created by Thomas Bröckers on 14.02.08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "DragController.h"


@implementation DragController

- (void) awakeFromNib {    
    
    songs = [[NSMutableArray alloc] init];
    [songTable registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]]; 
    
    [songTable setNextResponder: self];
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView {
    
    return [songs count];
}

- (id)              tableView:(NSTableView *) tableView 
    objectValueForTableColumn:(NSTableColumn *) tableColumn 
                          row:(int) row {
    
    return [songs objectAtIndex:row];
}

- (NSDragOperation) tableView:(NSTableView*) tv 
                 validateDrop:(id <NSDraggingInfo>) info 
                  proposedRow:(int) row 
        proposedDropOperation:(NSTableViewDropOperation) op {
    
    [tv setDropRow:[tv numberOfRows] dropOperation:NSTableViewDropAbove];
    return NSTableViewDropAbove;
}

- (BOOL)    tableView:(NSTableView*) tv 
           acceptDrop:(id <NSDraggingInfo>) info 
                  row:(int) row 
        dropOperation:(NSTableViewDropOperation) op {

    NSPasteboard *myPasteboard = [info draggingPasteboard];

    NSArray *typeArray = [NSArray arrayWithObjects:NSFilenamesPboardType, nil];
    NSString *filePath, *availableType;
    NSArray *filesList;
    int i;
    
    availableType = [myPasteboard availableTypeFromArray:typeArray];    
    filesList = [myPasteboard propertyListForType:availableType];
    
    for (i = 0;  i < [filesList count]; i++) {
        filePath = [filesList objectAtIndex:i];
        [songs insertObject:filePath atIndex:row+i];
    }
    
    [songTable reloadData];
    [songTable setNeedsDisplay:YES];
    
    return YES;
}

- (void) keyDown:(NSEvent *) event {
    
    if ([event keyCode] == 51 || [event keyCode] == 117) {
        [self deleteSelectedRowsInTableView:songTable
                               ForBaseArray:songs];
    } 
}

- (void) deleteSelectedRowsInTableView:(NSTableView *) tableView
                          ForBaseArray:(NSMutableArray *) baseArray {
    
    int row = [tableView selectedRow];
    
    if (row >= 0) {

        NSEnumerator *theEnum = [tableView selectedRowEnumerator];
        
        id theItem;
        while ((theItem = [theEnum nextObject]) != nil )
        {
            int row = [theItem intValue];
            [baseArray replaceObjectAtIndex:row withObject:[NSNull null]];
        }

        [baseArray removeObjectIdenticalTo:[NSNull null]];
        [tableView deselectAll:nil];
        [tableView reloadData];
        [tableView setNeedsDisplay:YES];
    }
}

- (NSMutableArray *) getSongs {
    return songs;
}


@end
